package com.samnative.pineapple.main;

import android.content.Context;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.EditorInfo;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.google.gson.reflect.TypeToken;
import com.kongzue.dialog.interfaces.OnDialogButtonClickListener;
import com.kongzue.dialog.util.BaseDialog;
import com.kongzue.dialog.v3.MessageDialog;
import com.samnative.pineapple.adapter.SearchHistoryAdapter;
import com.samnative.pineapple.http.HttpRequest;
import com.samnative.pineapple.http.JsonResult;
import com.samnative.pineapple.instance.AppPrefer;
import com.samnative.pineapple.utils.FileUtils;
import com.samnative.pineapple.utils.GsonUtils;
import com.samnative.pineapple.value.Config;
import com.samnative.pineapple.widget.TagCloudView;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 搜索
 *
 * @author WangPeng
 * <p>
 * EditText 自定义软键盘确定键 android:imeoptions="" actionNone : 回车键，按下后光标到下一行
 * actionGo ： Go， actionSearch ： 放大镜 actionSend ： Send actionNext ： Next
 * actionDone ：Done，确定/完成，隐藏软键盘，即使不是最后一个文本输入框
 */
public class SearchActivity extends BaseActivity implements OnClickListener,
        TextWatcher, OnItemClickListener, OnItemLongClickListener {

    /**
     * 搜索框
     */
    private EditText edName;
    /**
     * 上下文
     */
    private Context context;
    /**
     * 搜索历史
     */
    private List<String> listHistory;
    /**
     * 搜索历史列表适配器
     */
    private SearchHistoryAdapter shAdapter;
    /**
     * 历史列表显示
     */
    private ListView lv_history;
    /**
     * 显示热门标签
     */
    private TagCloudView tag_cloud_view;
    /**
     * 热门标签列表
     */
    private List<String> tags;
    /**
     * 搜索历史头部
     */
    private RelativeLayout rl_history;
    /**
     * 默认关键字
     */
    private String hintKey;
    /**
     * 热门字样
     */
    private TextView tv_hot;
    /**
     * 缓存路径
     */
    private String cachePath = "";

    /**
     * 搜索类型 1实体店 2商城 3商城店铺内
     */
    private int type;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_search;
    }

    @Override
    protected void initView(Bundle savedInstanceState) {
        super.initView(savedInstanceState);
        type = getIntent().getIntExtra("type", 2);
        context = this;
        cachePath = Config.MALL_CACHE_PATH;
        listHistory = new ArrayList<String>();
        tags = new ArrayList<>();
        shAdapter = new SearchHistoryAdapter(context, listHistory);
        lv_history = (ListView) findViewById(R.id.lv_history);
        lv_history.addHeaderView(headView());
        lv_history.setAdapter(shAdapter);
        lv_history.setOnItemClickListener(this);
        lv_history.setOnItemLongClickListener(this);
        findViewById(R.id.tv_back).setOnClickListener(this);
        findViewById(R.id.tv_search).setOnClickListener(this);
        edName = (EditText) findViewById(R.id.search_edit);
        edName.addTextChangedListener(this);
        // edName.setImeOptions(EditorInfo.IME_ACTION_SEARCH); //XML中设置
        // 监听软键盘确定键
        edName.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId,
                                          KeyEvent event) {
                // TODO Auto-generated method stub
                // 判断是否是“GO”键
                if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                    String content = edName.getText().toString();
                    if (content.isEmpty()) {
                        if (hintKey != null) {
                            content = hintKey;
                        } else {
                            return false;
                        }
                    }
                    saveHistoryData(content);
                    startNextActivity(content);
                }
                return false;
            }
        });
        requestKeywordData();
        getSearchHistory();
    }

    /**
     * 标签
     */
    private View headView() {
        View headView = LayoutInflater.from(context).inflate(
                R.layout.view_tagview, null);
        tv_hot = headView.findViewById(R.id.tv_hot);
        rl_history = (RelativeLayout) headView.findViewById(R.id.rl_history);
        tag_cloud_view = (TagCloudView) headView
                .findViewById(R.id.tag_cloud_view);
        tag_cloud_view.setTags(tags);
        tag_cloud_view.setOnTagClickListener(new TagCloudView.OnTagClickListener() {

            @Override
            public void onTagClick(int position) {
            }
        });
        headView.findViewById(R.id.tv_history_delete).setOnClickListener(this);
        return headView;
    }

    /**
     * 获取关键字
     *
     * @param
     */
    private void requestKeywordData() {
        // TODO Auto-generated method stub
        Map<String, String> map = new HashMap<String, String>();
        map.put("mtoken", AppPrefer.getInstance(mContext).getString(AppPrefer.mtoken, ""));
        map.put("type", type + "");
        map.put("_apiname", "mall.index.mallKeywords");


        HttpRequest.post(this, "", map, new JsonResult() {
            @Override
            public void reqestSuccess(JSONObject result) {

                try {
                    JSONObject jsonData = result
                            .getJSONObject("data");
                    hintKey = jsonData.optString("name");
                    if (!hintKey.isEmpty()){
                        edName.setHint(hintKey);
                    }
                    JSONArray jsonArr = jsonData
                            .getJSONArray("keywords");
                    tags = GsonUtils.fromJsonList(jsonArr.toString(),
                            new TypeToken<List<String>>() {
                            }.getType());
                    tag_cloud_view.setTags(tags);
                    tag_cloud_view
                            .setOnTagClickListener(new TagCloudView.OnTagClickListener() {

                                @Override
                                public void onTagClick(int position) {
                                    String content = tags.get(position);
                                    saveHistoryData(content);
                                    startNextActivity(content);
                                }
                            });
                    if (tags.size()>0){
                        tv_hot.setVisibility(View.VISIBLE);
                    }else{
                        tv_hot.setVisibility(View.GONE);
                    }
                } catch (JSONException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        });


    }

    /**
     * 获取搜索历史
     */
    public void getSearchHistory() {
        try {
            File file = new File(FileUtils.getCacheFile(context) + cachePath
                    + "/history_key");
            if (file.exists()) {
                List<String> historys = FileUtils.readFileToList(
                        file.getPath(), "UTF-8");
                listHistory.clear();
                listHistory.addAll(historys);
                shAdapter.notifyDataSetChanged();
            } else {
                listHistory.clear();
                shAdapter.notifyDataSetChanged();
            }
        } catch (Exception e) {
            // TODO: handle exception
            listHistory.clear();
            shAdapter.notifyDataSetChanged();
        }
        if (listHistory.size() == 0) {
            rl_history.setVisibility(View.GONE);
        } else {
            rl_history.setVisibility(View.VISIBLE);
        }
    }

    /**
     * 储存添加搜索历史记录
     *
     * @param content
     */
    public void saveHistoryData(String content) {
        for (int i = 0; i < listHistory.size(); i++) {
            if (listHistory.get(i).equals(content)) {
                listHistory.remove(i);
            }
        }

        if (listHistory.size() > 9) {
            List<String> temp = new ArrayList<String>();
            temp.addAll(listHistory.subList(0, 9));
            listHistory.clear();
            listHistory.addAll(temp);
        }

        listHistory.add(0, content);
        shAdapter.notifyDataSetChanged();
        FileUtils.writeFile(FileUtils.getCacheFile(context) + cachePath
                + "/history_key", listHistory);
    }

    @Override
    protected void onDestroy() {
        // TODO Auto-generated method stub
        super.onDestroy();
    }

    /**
     * 点击监听
     */
    @Override
    public void onClick(View v) {
        // TODO Auto-generated method stub
        switch (v.getId()) {
            case R.id.tv_back:
                finish();
                break;
            case R.id.tv_search:
                String content = edName.getText().toString();
                if (content.isEmpty()) {
                    if (hintKey != null) {
                        content = hintKey;
                    } else {
                        break;
                    }
                }
                saveHistoryData(content);
                startNextActivity(content);
                break;
            case R.id.tv_history_delete:

                MessageDialog.show(this, null, "是否清空搜索记录", getString(R.string.confirm), getString(R.string.cancel)).setOnOkButtonClickListener(
                        new OnDialogButtonClickListener() {
                            @Override
                            public boolean onClick(BaseDialog baseDialog, View v) {
                                listHistory.clear();
                                shAdapter.notifyDataSetChanged();
                                rl_history.setVisibility(View.GONE);
                                File cacheFile = new File(FileUtils.getCacheFile(context)
                                        + cachePath + "/history_key");
                                cacheFile.delete();
                                return false;
                            }
                        });


                break;
            default:
                break;
        }
    }

    /**
     * 跳转到下个页面
     *
     * @param title
     */
    public void startNextActivity(String title) {
        // 跳转到搜索结果列表

    }

    // =================输入框改变监听================Start

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count,
                                  int after) {
        // TODO Auto-generated method stub

    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {
        // TODO Auto-generated method stub

    }

    @Override
    public void afterTextChanged(Editable s) {
        // TODO Auto-generated method stub
    }

    // =================输入框改变监听================End

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position,
                            long id) {
        // TODO Auto-generated method stub
        int newPosition = position - 1;
        if (newPosition <= 0) {
            newPosition = 0;
        }
        if (listHistory.size() <= newPosition) {
            return;
        }
        String content = listHistory.get(newPosition);
        saveHistoryData(content);
        startNextActivity(content);
    }

    @Override
    protected void onPause() {
        super.onPause();
    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    // ======================================================

    @Override
    public boolean onItemLongClick(AdapterView<?> parent, View view,
                                   final int position, long id) {
        // TODO Auto-generated method stub


        MessageDialog.show(this, null, "是否删除该记录", getString(R.string.confirm), getString(R.string.cancel)).setOnOkButtonClickListener(
                new OnDialogButtonClickListener() {
                    @Override
                    public boolean onClick(BaseDialog baseDialog, View v) {
                        int newPosition = position - 1;
                        if (newPosition <= 0) {
                            newPosition = 0;
                        }
                        listHistory.remove(newPosition);
                        shAdapter.notifyDataSetChanged();
                        FileUtils.writeFile(FileUtils.getCacheFile(context)
                                + cachePath + "/history_key", listHistory);
                        return false;
                    }
                });


        return true;
    }

}
